﻿using Microsoft.Extensions.Options;
using Shop.Core.Alibaba;
using Shop.Core.Helper;
using Shop.Core.Repository;
using Shop.Core.Share;
using Shop.Model.Dto.Common;
using Shop.Model.Entity.System;
using Shop.Model.View.Common;

namespace Shop.IServices
{
    /// <summary>
    /// 阿里云服务
    /// </summary>
    public class AliyunAppService : IAliyunAppService
    {
        private readonly IOptions<AlibabaConfig> _config;

        private readonly RepositoryBase<SmsLog> _smsLogRepository;
        public AliyunAppService(IOptions<AlibabaConfig> config
            ,RepositoryBase<SmsLog> smsLogRepository)
        {
            _config = config;
            _smsLogRepository = smsLogRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public OssSignDto GetOssSign(string dir)
        {
            OSS oss = new(_config.Value);
            var data = oss.OssSign(dir);
            return new OssSignDto()
            {
                AccessKeyId = data.AccessKeyId,
                Dir = data.Dir,
                Host = data.Host,
                Expire = data.Expire,
                Policy = data.Policy,
                Signature = data.Signature,
            };
        }

        public async Task<AppResult> SendSms(SendSmsDto input)
        {
            Sms sms = new(_config.Value);
            var res = sms.SendSms(input.Tel, "迪娅尔", input.Temp, input.TempParam);
            await _smsLogRepository.InsertAsync(new SmsLog
            {
                Code = res.Code,
                Bizld = res.BizId,
                Message = res.Message,
                Requestld = res.RequestId,
                SenData = input.TempParam,
                SenTemp = input.Temp,
                Tel = input.Tel,
                SendTime = DateTime.Now,
            });
            return res.Code switch
            {
                "OK" => new AppResult(),
                "isv.BUSINESS_LIMIT_CONTROL" => new AppResult() { Code = 400, Message = "失败", Errors = new string[] { "短信发送频繁，请稍后再发" } },
                "isv.DAY_LIMIT_CONTROL" => new AppResult() { Code = 400, Message = "失败", Errors = new string[] { "短信发送频繁，请明天再发" } },
                "isv.OUT_OF_SERVICE" => new AppResult() { Code = 400, Message = "失败", Errors = new string[] { "业务停机" } },
                "isv.ACCOUNT_ABNORMAL" => new AppResult() { Code = 400, Message = "失败", Errors = new string[] { "账户异常" } },
                "isp.SYSTEM_ERROR" => new AppResult() { Code = 400, Message = "失败", Errors = new string[] { "系统错误" } },
                "isv.MOBILE_NUMBER_ILLEGAL" => new AppResult() { Code = 400, Message = "失败", Errors = new string[] { "非法手机号" } },
                _ => new AppResult() { Code = 400, Message = "失败", Errors = new string[] { "短信发送失败" } },
            };
        }
    }
}
